from flask import(
    g, Blueprint, render_template, request, session, url_for, redirect, current_app
)

user_bp = Blueprint('user', __name__, url_prefix='/user')

# 修改个人信息路透
@user_bp.route('/edit_myProfile', methods=['GET', 'POST'])
def edit_myProfile():
    if request.method == 'POST':
        print('有信息到来')
        # 获取user_id 
        user_id = g.user_id

        # 获取信息 用户名，性别，国家，联系方式
        username = request.form['username']
        gender = request.form['gender']
        country = request.form['country']
        email = request.form['email']
        print(username, gender, country, email)
        # 连接数据库
        db_pool = current_app.db_pool
        db_conn = g.db_conn
        db_cursor = g.db_cursor

        # 更新数据库
        sql = "UPDATE user_info SET name = %s, gender = %s, country = %s, email = %s WHERE user_id = %s"
        try:
            db_pool.execute_update(db_conn, sql, db_cursor, (username, gender, country, email, user_id))
        except:
            flash('更新失败')

        # 个人信息页面
        return redirect(url_for('user.myProfile'))
    return render_template('user/edit_myProfile.html')
        
@user_bp.route('/myProfile')
def myProfile():
    
    # 获取user_id 
    user_id = g.user_id # 避免多次访问session_id，似乎可以避免I/O的次数（Redis的情况下）
    print('-'*30, user_id, '-'*30)
    db_pool = current_app.db_pool
    db_conn = g.db_conn
    db_cursor = g.db_cursor

    # 查找数据库用户信息表
    sql = "SELECT * FROM user_info WHERE user_id = %s"

    user_info = db_pool.execute_query(db_conn, sql, db_cursor, args=(user_id,), fetchone=True)
    print('查询结果：')
    print(user_info)
    # 传入给模板
    return render_template('user/myProfile.html', user_info=user_info)